package io.vertx.examples.spring;


import io.vertx.examples.spring.common.DateTimeUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

public class MockHttp {

    public static final AtomicLong idGenerator = new AtomicLong(0);

    private static final String URL_STR = "http://localhost:8089/productList";

    public static void main(String[] args) throws Exception {

        int count = 100;
        ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(count);
        for(int i=1;i<=count;i++){
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    String path = "02.jpg";
                    httpRequest(path,0);
                }
            });
        }
        while (true){
            if (executorService.getCompletedTaskCount() == count){
                executorService.shutdown();
                System.out.println("task over");
                break;
            }else{
                //showLog(executorService);
                Thread.sleep(1000*2);
            }
        }
    }

    private static void showLog(ThreadPoolExecutor executor) {
        System.out.println("*********************");
        System.out.println("Main: 线程池监控");
        System.out.println("Main: Executor: 内部线程池的真实大小: {}"+ executor.getPoolSize());
        System.out.println("Main: Executor: 当前执行任务的线程数:{}"+executor.getActiveCount());
        System.out.println("Main: Executor: 已经分配执行的任务数: {}"+ executor.getTaskCount());
        System.out.println("Main: Executor: 已经完成执行的任务数: {}"+ executor.getCompletedTaskCount());
        System.out.println("*********************");
    }


    public static void httpRequest(String localFile, int count) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();

            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost(URL_STR);

            httpPost.addHeader("device_no", "68c7da9e");
            // 把文件转换成流对象FileBody
//            FileBody file = new FileBody(new File(localFile));


            StringBody cou = new StringBody("123"+count, ContentType.create(
                    "text/plain", Consts.UTF_8));

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    // 相当于<input type="file" name="file"/>
//                    .addPart("img", file)
                    // 相当于<input type="text" name="userName" value=userName>
                    .addPart("key", cou)
                    .build();

            httpPost.setEntity(reqEntity);

            // 发起请求 并返回请求的响应
            System.out.println(Thread.currentThread().getName()+" start time: "+ DateTimeUtils.now(DateTimeUtils.YYYYMMDDHHMMSS_SPLIT));
            response = httpClient.execute(httpPost);
            System.out.println(Thread.currentThread().getName()+" end   time: "+DateTimeUtils.now(DateTimeUtils.YYYYMMDDHHMMSS_SPLIT));
//            System.out.println("The response value of token:" + response.getFirstHeader("token"));

            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应长度
//                System.out.println("Response content length: " + resEntity.getContentLength());
                // 打印响应内容
                //System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
            }

            // 销毁
            EntityUtils.consume(resEntity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static ByteArrayOutputStream parse(InputStream in) throws Exception
    {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = in.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream;
    }

}
